<?php

namespace App\Services;

use App\Exceptions\InternalException;
use App\Models\MaterialDelivery;
use Illuminate\Support\Facades\Log;

class MaterialDeliveryService
{
    public function get(){
        $sql = MaterialDelivery::with('application')->with('project')->with('user');
        return $sql;
    }

    public function insert($input){
        $res = [];
        foreach ($input as $k => $v) {
            if($v){
                $res[$k] = $v;
            }
        }

        $arr = [];
        $details = $input['data'];
        foreach ($details as $key => $value) {
            $arr_ = [];
            $arr_['title'] = $value->title;
            $arr_['material_id'] = $input['material_id'];
            $arr_['user_id'] = $input['user_id'];
            $arr_['specs'] = $value->specs;
            $arr_['project_id'] = $input['project_id'];
            $arr_['price'] = $value->price;
            $arr_['sums'] = $value->sums;
            $arr_['unit_price'] = $value->unit_price;
            $arr_['unit'] = $value->unit;
            $arr_['remarks'] = 0;
            $arr_['created_at'] = Date("Y-m-d H:i:s",time());
            $arr_['updated_at'] = Date("Y-m-d H:i:s",time());
            $arr[] = $arr_;
        }

        try {
            MaterialDelivery::where('material_id',$input['material_id'])->delete();
            $data = MaterialDelivery::insert($arr);
            return $data;
        } catch (\Throwable $th) {
            Log::info(json_encode($th));
            throw new InternalException('提交失败');
        }
    }

    public function update($input){
        $res = [];
        foreach ($input as $k => $v) {
            $v = $v === null ? '/' : $v;
            if($v){
                $res[$k] = $v;
            }
        }
        $arr = [];
        $details = $input['data'];
        foreach ($details as $key => $value) {
            $arr_ = [];
            $arr_['title'] = $value->title;
            $arr_['material_id'] = $input['material_id'];
            $arr_['user_id'] = $input['user_id'];
            $arr_['specs'] = $value->specs;
            $arr_['project_id'] = $input['project_id'];
            $arr_['price'] = $value->price;
            $arr_['sums'] = $value->sums;
            $arr_['unit_price'] = $value->unit_price;
            $arr_['unit'] = $value->unit;
            $arr_['remarks'] = 0;
            $arr_['created_at'] = Date("Y-m-d H:i:s",time());
            $arr_['updated_at'] = Date("Y-m-d H:i:s",time());
            $arr[] = $arr_;
        }
        try {
            MaterialDelivery::where('material_id',$input['material_id'])->delete();
            MaterialDelivery::insert($arr);
        } catch (\Throwable $th) {
            Log::info(json_encode($th));
            throw new InternalException($th);
        }
    }
}